package top.hyperplasma.kinare.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.hyperplasma.kinare.domain.dto.ChatRequest;
import top.hyperplasma.kinare.domain.dto.ChatResponse;
import top.hyperplasma.kinare.service.OpenAIService;

@Slf4j
@RestController
@RequestMapping("/api/openai")
@Tag(name = "OpenAI Chat API", description = "OpenAI chat completion endpoints")
public class OpenAIController {

    @Autowired
    private OpenAIService openAIService;

    @Operation(summary = "Chat with AI", description = "Send a prompt to OpenAI and get a response")
    @PostMapping("/chat")
    public ResponseEntity<ChatResponse> chat(@Valid @RequestBody ChatRequest request) {
        log.info("Received chat request with prompt: {}", request.getPrompt());
        try {
            ChatResponse response = openAIService.generateResponse(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error while processing chat request", e);
            return ResponseEntity.internalServerError()
                    .body(ChatResponse.builder()
                            .status("error")
                            .message("Error processing request: " + e.getMessage())
                            .timestamp(System.currentTimeMillis())
                            .build());
        }
    }
}